public class class02 {
    public class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public boolean isBalanced(TreeNode root) {
        if(root==null){
            return true;
        }
        return getHeight(root) >= 0;
    }

    public int getHeight(TreeNode root){
        if (root == null){
            return 0;
        }

        int leftHeight = getHeight(root.left);
        if(leftHeight<0){
            return -1;
        }
        int rightHeight = getHeight(root.right);
        if(leftHeight >= 0 && rightHeight >= 0 && Math.abs(leftHeight-rightHeight)<=1){
            return Math.max(leftHeight,rightHeight)+1;
        }else{
            return -1;
        }
    }
}
